package com.neuedu.his.framework.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.neuedu.his.entity.User;
import com.neuedu.his.framework.CommonResult;
import com.neuedu.his.framework.annotation.MethodAlias;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 项目：      his
 * 类名:       BaseServlet
 * 创建时间：  2020/12/22  11:04
 * 描述 :     基础Servlet
 * 作者 :     张金山
 * QQ :     314649444
 * Site:      https://jshand.gitee.io
 */

public class BaseServlet extends HttpServlet {

    private static List<SimpleDateFormat> sdfs = new ArrayList();

    static {
        //格式化日期的 模式
        sdfs.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        sdfs.add(new SimpleDateFormat("yyyy-MM-dd"));
        sdfs.add(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"));
        sdfs.add(new SimpleDateFormat("yyyy/MM/dd"));
    }


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String function = request.getParameter("type");

        Class<? extends BaseServlet> clazz = this.getClass();

        Method invokeMethod = null;
        try {

            //首先根据查找注解为function的
            Method[] methods = clazz.getDeclaredMethods();

            for (Method method : methods) {
                // http://127.0.0.1:8080/his/user?type=query
                MethodAlias anno = method.getAnnotation(MethodAlias.class);
                if (anno != null && anno.value().equals(function)) {
                    invokeMethod = method;
                    break;
                }
            }

            if (invokeMethod == null) {
                // http://127.0.0.1:8080/his/user?type=add
                // http://127.0.0.1:8080/his/user?type=list
                invokeMethod = clazz.getDeclaredMethod(function, HttpServletRequest.class, HttpServletResponse.class);
            }

            invokeMethod.invoke(this, request, response);

        } catch (NoSuchMethodException e) {
            System.err.println("NoSuchMethodException 请求无法处理，未找到方法:\r\n" + e.getMessage());
            CommonResult result = CommonResult.noHanlder();// {code 404 ，msg :‘为找到处理方法’}
            this.out(response, result);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            CommonResult result = CommonResult.error("系统出错了，请联系管理员" + e.getMessage());
            this.out(response, result);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }


    protected <T> T parseParameter(HttpServletRequest request, Class<T> clazz) throws IllegalAccessException, InstantiationException {

        T obj = clazz.newInstance();

        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String paramName = names.nextElement();

            String value = request.getParameter(paramName);

            try {
                Field field = clazz.getDeclaredField(paramName);
                field.setAccessible(true);
                setFiledValue(field, obj, value);
            } catch (Exception e) {
                //e.printStackTrace();
            }
        }

        return obj;
    }


    private void setFiledValue(Field field, Object obj, String value) throws IllegalAccessException, ParseException {
        //根据属性类型，将value转换成  Integer、 Date
        String type = field.getType().getName();
        if ("java.lang.Integer".equals(type)) {
            field.set(obj, Integer.parseInt(value));
        } else if ("java.util.Date".equals(type)) {
            Date date = null;

            for (SimpleDateFormat sdf : sdfs) {
                try { // 正则表达式批
                    date = sdf.parse(value);
                    break;
                } catch (Exception e) {
                }
            }

            if (date != null) {
                field.set(obj, date);
            } else {
                System.err.println("日期 参数转换出错：属性名：【" + field.getName() + "】 value:"+value);
            }

        } else if ("java.math.BigDecimal".equals(type)) {
            field.set(obj, new BigDecimal(value));
        } else {
            field.set(obj, value);
        }
    }


    protected void success(HttpServletResponse response, Object data) throws IOException {
        CommonResult result = CommonResult.success(data);// {code 404 ，msg :‘为找到处理方法’}
        this.out(response, result);

    }


    private void out(HttpServletResponse response, Object data) throws IOException {

        response.setContentType("application/json");

        String json = JSON.toJSONString(data, SerializerFeature.WriteDateUseDateFormat);
        PrintWriter out = response.getWriter();
        out.write(json);
        out.flush();
        out.close();
    }


}
